<?php
class HumanResourcesController extends AppController {

	var $name = 'HumanResources';
	
	public function beforeFilter() {
            parent::beforeFilter();
            //$this->Auth->allow('index');
        }
	
	function index()
	{
		Controller::loadModel('CityDetail');
		$city_id = $this->Session->read("c_city_id");
		$year = $this->Session->read("c_year");
		$quarter = $this->Session->read("c_quarter");
		$this->layout = "home";
		//Listing branches
		$branches = $this->HumanResource->Branch->find('all',array(								  
									'fields' => array('Branch.id', 'Branch.name', 'Branch.city_id'),
									'conditions' => array(
												'Branch.city_id'=>$city_id
											),
								));
		//Listing employees
		$employees = $this->HumanResource->Employee->find('all',array(
								  
									'fields' => array('Employee.id', 'Employee.name'),
									'conditions'=>array('Employee.nhd !='=>1)
									
								));		
		//create values array for rendering view
		//$humanresource_string = '[';
		//$line_array = array();
		//$tick_array = array();
		
		//check if have value yet
		$notEmpty = $this->HumanResource->find("count", array(
											'conditions' => array(
												'HumanResource.value !=' => "",
												'HumanResource.year' => $year,
												'HumanResource.quarter' => $quarter
											)
										));
		//echo $notEmpty;
		
		$bs_rhm = 0;
		foreach($employees as $e => $employee)
		{
			$employees[$e]["total"] = 0;
			$o_array = array();
			foreach($branches as $b => $branch)
			{
				$humanresource = $this->HumanResource->find("first", array(
											'conditions' => array(
												'HumanResource.branch_id' => $branch["Branch"]["id"],
												'HumanResource.employee_id' => $employee["Employee"]["id"],
												'HumanResource.year' => $year,
												'HumanResource.quarter' => $quarter
											)
										));
				$values[$branch["Branch"]["id"]][$employee["Employee"]["id"]] = $humanresource["HumanResource"]["value"];
				
				//sum employee
				if($humanresource["HumanResource"]["value"] != '')
					$employees[$e]["total"] = $employees[$e]["total"] + $humanresource["HumanResource"]["value"];
					
				
				//BS RHM
				if(in_array($employee['Employee']['id'], array(1,2)) && $humanresource["HumanResource"]["value"] != '')
				{
					$bs_rhm += $humanresource["HumanResource"]["value"];
				}
			}
		}
		//echo $bs_rhm;
		$danso = $this->CityDetail->find("first", array(
											'conditions' => array(
												'CityDetail.city_id' => $city_id,
												'CityDetail.year' => $year
											)
										));
		$bs_dan = $bs_rhm ? round($danso['CityDetail']['population']/$bs_rhm, 0) : 0;
		
		$tick_a = array();
		$value_a = array();
		foreach($employees as $e => $employee)
		{
			$value_a[] = $employee["total"];
			$tick_a[] = $employee["Employee"]["name"];
		}
		$value_s = '['.implode(',', $value_a).']';
		$tick_s = '["'.implode('","', $tick_a).'"]';
		
		$this->data["HumanResource"]["unit_id"] = !empty($this->data["HumanResource"]["unit_id"])?$this->data["HumanResource"]["unit_id"]:1;
		
		$this->set(compact('branches', 'employees', 'values', 'tick_s', 'value_s', 'bs_dan', 'notEmpty'));
	}

	function manager_index() {
		$this->HumanResource->recursive = 0;
		Controller::loadModel('Branch');
		
		$c_year = $this->Session->read("c_year");
		
		//get cities list
		Controller::loadModel('City');
		$user = $this->Auth->user();
		$cities = $this->City->citiesByUser($user["User"]["id"]);
		//var_dump($cities);
		$conditions = array();
		
		//filter city id
		$city_id = !empty($this->params['form']['filter_city_id']) && $this->params['form']['filter_city_id'] != "" ? $this->params['form']['filter_city_id'] : $cities[0]["City"]["id"];
		if($city_id)
		{
			$conditions["Branch.city_id"] = $city_id;
		}
		
		//filter branch
		$branches = $this->Branch->find("all", array('conditions' => array('Branch.city_id'=>$city_id)));
		$branch_id = !empty($this->params['form']['filter_branch_id']) && $this->params['form']['filter_branch_id'] != "" ? $this->params['form']['filter_branch_id'] : 0;
		if($branch_id)
		{
			$conditions["Branch.id"] = $branch_id;
		}
		
		//filter year
		$year = !empty($this->params['form']['filter_year']) && $this->params['form']['filter_year'] != "" ? $this->params['form']['filter_year'] : $c_year;
		if($year)
		{
			$conditions["HumanResource.year"] = $year;
		}
		
		
		//var_dump($this->params);
		if(count($conditions))
		{
			$this->paginate = array(
				'conditions' => $conditions				
			);
		}
		
		$this->set('humanResources', $this->paginate());
		$this->set('cities', $cities);
		$this->set('branches', $branches);
		$this->set('city_id', $city_id);
		$this->set('branch_id', $branch_id);
		$this->set('year', $year);
	}

	function manager_view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid human resource', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('humanResource', $this->HumanResource->read(null, $id));
	}
	
	function admin_add() {
		if(!$this->Session->read("isActive"))
		{
			$this->redirect(array('controller'=>'users' , 'action' => 'offline', 'manager'=>false));
		}
		
		Controller::loadModel('City');
		Controller::loadModel('User');
		$users = $this->HumanResource->User->find('list');
		//$city = $this->City->find("first");
		
		$c_year = $this->Session->read("c_year");
		$c_quarter = $this->Session->read("c_quarter");
		
		
		//Check if user have role on city
		$user = $this->Auth->user();
		$user = $this->HumanResource->User->find("first", array(
									'conditions'=>array('User.id'=>$user["User"]["id"])									
								));		
		
		//find city_id
		$cities = $user["City"];
		if(!empty($this->params['form']['filter_city_id']))
		{
			foreach($cities as $c)
			{
				if($c["id"] == $this->params['form']['filter_city_id'])
				{
					$city = $c;
					break;
				}
			}
		}
		else if(!empty($this->data["HumanResource"]["city_id"]))
		{
			$city = $this->City->find("first", array(
									'conditions'=>array('City.id'=>$this->data["HumanResource"]["city_id"])									
								));
			$city = $city["City"];
		}
		else
		{
			$city = $user["City"][0];
		}
		
		
		//Listing branches
		$branches = $this->HumanResource->Branch->find('all',array(								  
									'fields' => array('Branch.id', 'Branch.name', 'Branch.city_id'),
									'conditions' => array(
												'Branch.city_id'=>$city["id"]
											),
								));
		//Listing employees
		$employees = $this->HumanResource->Employee->find('all',array(
								  
									'fields' => array('Employee.id', 'Employee.name'),
									'conditions'=>array('Employee.nhd !='=>1)
									
								));		
		
		$year = !empty($this->params['form']['filter_year']) ? $this->params['form']['filter_year'] : $c_year;
		$quarter = !empty($this->params['form']['filter_quarter']) ? $this->params['form']['filter_quarter'] : $c_quarter;
		//$year = date('Y');
		//$quarter = date('m')%3 + 1;
		
		$user = $this->Auth->user();
		
		//echo $user["User"]["id"];
		
		
		//check if the user has accessibility to city					
		if(!$this->User->isUserCity($user["User"]["id"], $city["id"]))
		{
			$this->Session->setFlash(__('Manager doesn\'t has role on this city', true));
			$this->redirect(array('action' => 'index'));
		}
			
			
		
		if (!empty($this->data)) {			
			//Saving humanresource values
			foreach($branches as $b => $branch)
			{
				foreach($employees as $e => $employee)
				{
					$value = $this->data["values"][$branch["Branch"]["id"]][$employee["Employee"]["id"]];
					
					//Convert to good-looking number
					$value = str_replace(",", "", $value);
					
					//check if record exsits
					$exsit = $this->HumanResource->find("first", array(
											'conditions' => array(
												'HumanResource.branch_id' => $branch["Branch"]["id"],
												'HumanResource.employee_id' => $employee["Employee"]["id"],
												'HumanResource.year' => $this->data["HumanResource"]["year"],
												'HumanResource.quarter' => $this->data["HumanResource"]["quarter"]
											)
										));
						
					//echo $exsit["HumanResource"]["id"];
					$humanresource = $this->data;
					$humanresource["HumanResource"]["value"] = $value;
					$humanresource["HumanResource"]["city_id"] = $branch["Branch"]["city_id"];
					$humanresource["HumanResource"]["branch_id"] = $branch["Branch"]["id"];
					$humanresource["HumanResource"]["employee_id"] = $employee["Employee"]["id"];
					$humanresource["HumanResource"]["user_id"] = $user["User"]["id"];
					
					//echo $humanresource["HumanResource"]["value"];					
						
					
					if(empty($exsit["HumanResource"]["id"]))
					{
						if($value != "") //if there first record, create record and store the value
						{						
							$this->HumanResource->create();
							if ($this->HumanResource->save($humanresource)) {
							$this->Session->setFlash(__('Thông tin nhân lực đã được cập nhật', true));
							//$this->redirect(array('action' => 'index'));							
							//break;
							} else {
								$this->Session->setFlash(__('The human resource could not be saved. Please, try again.', true));
							}
						}					
					}
					else //if record exsits, change its value
					{
						$humanresource["HumanResource"]["id"] = $exsit["HumanResource"]["id"];
						//echo $value."o";
						if ($this->HumanResource->save($humanresource)) {
							$this->Session->setFlash(__('Thông tin nhân lực đã được cập nhật', true));
							//$this->redirect(array('action' => 'index'));							
							//break;
						} else {
							$this->Session->setFlash(__('The human resource could not be saved. Please, try again.', true));
						}
					}					
				}
			}
			$year = $this->data["HumanResource"]["year"];
			$quarter = $this->data["HumanResource"]["quarter"];
		}
		
		//create values array for rendering view
		foreach($branches as $b => $branch)
		{
			foreach($employees as $e => $employee)
			{
				$humanresource = $this->HumanResource->find("first", array(
											'conditions' => array(
												'HumanResource.branch_id' => $branch["Branch"]["id"],
												'HumanResource.employee_id' => $employee["Employee"]["id"],
												'HumanResource.year' => $year,
												'HumanResource.quarter' => $quarter
											)
										));
				$values[$branch["Branch"]["id"]][$employee["Employee"]["id"]] = $humanresource["HumanResource"]["value"];
			}
		}
		
		//listing unit
		$units = $this->HumanResource->Unit->find('list');
		$this->data["HumanResource"]["unit_id"] = !empty($this->data["HumanResource"]["unit_id"])?$this->data["HumanResource"]["unit_id"]:1;
		
		$this->set(compact('users', 'cities', 'branches', 'employees', 'values', 'year', 'quarter', 'city', 'units'));
	}

	function manager_add() {
		if(!$this->Session->read("isActive"))
		{
			$this->redirect(array('controller'=>'users' , 'action' => 'offline', 'manager'=>false));
		}
		
		Controller::loadModel('City');
		Controller::loadModel('User');
		$users = $this->HumanResource->User->find('list');
		//$city = $this->City->find("first");
		
		$c_year = $this->Session->read("c_year");
		$c_quarter = $this->Session->read("c_quarter");
		
		
		//Check if user have role on city
		$user = $this->Auth->user();
		$user = $this->HumanResource->User->find("first", array(
									'conditions'=>array('User.id'=>$user["User"]["id"])									
								));		
		
		//find city_id
		$cities = $user["City"];
		if(!empty($this->params['form']['filter_city_id']))
		{
			foreach($cities as $c)
			{
				if($c["id"] == $this->params['form']['filter_city_id'])
				{
					$city = $c;
					break;
				}
			}
		}
		else if(!empty($this->data["HumanResource"]["city_id"]))
		{
			$city = $this->City->find("first", array(
									'conditions'=>array('City.id'=>$this->data["HumanResource"]["city_id"])									
								));
			$city = $city["City"];
		}
		else
		{
			$city = $user["City"][0];
		}
		
		
		//Listing branches
		$branches = $this->HumanResource->Branch->find('all',array(								  
									'fields' => array('Branch.id', 'Branch.name', 'Branch.city_id'),
									'conditions' => array(
												'Branch.city_id'=>$city["id"]
											),
								));
		//Listing employees
		$employees = $this->HumanResource->Employee->find('all',array(
								  
									'fields' => array('Employee.id', 'Employee.name'),
									'conditions'=>array('Employee.nhd !='=>1)
									
								));		
		
		//$year = !empty($this->params['form']['filter_year']) ? $this->params['form']['filter_year'] : $c_year;
		//$quarter = !empty($this->params['form']['filter_quarter']) ? $this->params['form']['filter_quarter'] : $c_quarter;
		$year = date('Y');
		$quarter = round(date('m')/3,0);
		
		$user = $this->Auth->user();
		
		//echo $user["User"]["id"];
		
		
		//check if the user has accessibility to city					
		if(!$this->User->isUserCity($user["User"]["id"], $city["id"]))
		{
			$this->Session->setFlash(__('Manager doesn\'t has role on this city', true));
			$this->redirect(array('action' => 'index'));
		}
			
			
		
		if (!empty($this->data)) {			
			//Saving humanresource values
			foreach($branches as $b => $branch)
			{
				foreach($employees as $e => $employee)
				{
					$value = $this->data["values"][$branch["Branch"]["id"]][$employee["Employee"]["id"]];
					
					//Convert to good-looking number
					$value = str_replace(",", "", $value);
					
					//check if record exsits
					$exsit = $this->HumanResource->find("first", array(
											'conditions' => array(
												'HumanResource.branch_id' => $branch["Branch"]["id"],
												'HumanResource.employee_id' => $employee["Employee"]["id"],
												'HumanResource.year' => $this->data["HumanResource"]["year"],
												'HumanResource.quarter' => $this->data["HumanResource"]["quarter"]
											)
										));
						
					//echo $exsit["HumanResource"]["id"];
					$humanresource = $this->data;
					$humanresource["HumanResource"]["value"] = $value;
					$humanresource["HumanResource"]["city_id"] = $branch["Branch"]["city_id"];
					$humanresource["HumanResource"]["branch_id"] = $branch["Branch"]["id"];
					$humanresource["HumanResource"]["employee_id"] = $employee["Employee"]["id"];
					$humanresource["HumanResource"]["user_id"] = $user["User"]["id"];
					
					//echo $humanresource["HumanResource"]["value"];					
						
					
					if(empty($exsit["HumanResource"]["id"]))
					{
						if($value != "") //if there first record, create record and store the value
						{						
							$this->HumanResource->create();
							if ($this->HumanResource->save($humanresource)) {
							$this->Session->setFlash(__('Thông tin nhân lực đã được cập nhật', true));
							//$this->redirect(array('action' => 'index'));							
							//break;
							} else {
								$this->Session->setFlash(__('The human resource could not be saved. Please, try again.', true));
							}
						}					
					}
					else //if record exsits, change its value
					{
						$humanresource["HumanResource"]["id"] = $exsit["HumanResource"]["id"];
						//echo $value."o";
						if ($this->HumanResource->save($humanresource)) {
							$this->Session->setFlash(__('Thông tin nhân lực đã được cập nhật', true));
							//$this->redirect(array('action' => 'index'));							
							//break;
						} else {
							$this->Session->setFlash(__('The human resource could not be saved. Please, try again.', true));
						}
					}					
				}
			}
			$year = $this->data["HumanResource"]["year"];
			$quarter = $this->data["HumanResource"]["quarter"];
		}
		
		//create values array for rendering view
		foreach($branches as $b => $branch)
		{
			foreach($employees as $e => $employee)
			{
				$humanresource = $this->HumanResource->find("first", array(
											'conditions' => array(
												'HumanResource.branch_id' => $branch["Branch"]["id"],
												'HumanResource.employee_id' => $employee["Employee"]["id"],
												'HumanResource.year' => $year,
												'HumanResource.quarter' => $quarter
											)
										));
				$values[$branch["Branch"]["id"]][$employee["Employee"]["id"]] = $humanresource["HumanResource"]["value"];
			}
		}
		
		//listing unit
		$units = $this->HumanResource->Unit->find('list');
		$this->data["HumanResource"]["unit_id"] = !empty($this->data["HumanResource"]["unit_id"])?$this->data["HumanResource"]["unit_id"]:1;
		
		$this->set(compact('users', 'cities', 'branches', 'employees', 'values', 'year', 'quarter', 'city', 'units'));
	}
	
	function manager_edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid human resource', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			
			//check if the user has accessibility to city
			Controller::loadModel('Branch');
			$user = $this->Auth->user();
			$branch = $this->Branch->read(null, $this->data["HumanResource"]["branch_id"]);
			Controller::loadModel('User');
			if(!$this->User->isUserCity($user["User"]["id"], $branch["Branch"]["city_id"]))
			{
				$this->Session->setFlash(__('Manager doesn\'t has role on this city', true));
				$this->redirect(array('action' => 'index'));
			}
			
			
			if ($this->HumanResource->save($this->data)) {
				$this->Session->setFlash(__('The human resource has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The human resource could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->HumanResource->read(null, $id);
			$year = $this->data["HumanResource"]["year"];
			
			Controller::loadModel('Branch');
			$user = $this->Auth->user();
			$branch = $this->Branch->read(null, $this->data["HumanResource"]["branch_id"]);
			Controller::loadModel('User');
		}
		$users = $this->HumanResource->User->find('list');
		$branches = $this->HumanResource->Branch->find('list', array('conditions'=>array('Branch.city_id'=>$branch["Branch"]["city_id"])));
		$employees = $this->HumanResource->Employee->find('list');
		$this->set(compact('users', 'cities', 'branches', 'employees', 'year'));
	}

	function manager_delete($id = null) {
		
		
		
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for human resource', true));
			$this->redirect(array('action'=>'index'));
		}
			
			//check if user has role on city
			$this->data = $this->HumanResource->read(null, $id);
			//check if the user has accessibility to city
			Controller::loadModel('Branch');
			$user = $this->Auth->user();
			$branch = $this->Branch->read(null, $this->data["HumanResource"]["branch_id"]);
			Controller::loadModel('User');
			if(!$this->User->isUserCity($user["User"]["id"], $branch["Branch"]["city_id"]))
			{
				$this->Session->setFlash(__('Manager doesn\'t has role on this city', true));
				$this->redirect(array('action' => 'index'));
			}
		
		
		if ($this->HumanResource->delete($id)) {
			$this->Session->setFlash(__('Human resource deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Human resource was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
}
